package com.example.client;

import lombok.Getter;
import lombok.Setter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.common.util.JsonParserFactory;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.util.StringUtils;

import javax.persistence.*;
import java.util.*;

/**
 * @author wangbin
 */
@Entity
@Table(name = "t_client")
@Getter
@Setter
public class Client implements ClientDetails {
    private static final long serialVersionUID = 72684248883284681L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(nullable = false, unique = true)
    private String clientId;
    @Column(nullable = false)
    private String clientSecret;
    @Column(nullable = false)
    private Integer accessTokenValiditySeconds;
    @Column(nullable = false)
    private Integer refreshTokenValiditySeconds;
    @Column(nullable = false)
    private String authorizedGrantTypes;

    private String scope;
    private String resourceIds;
    private String authorities;
    private String additionalInformation;
    private String autoApproveScope;
    private String registeredRedirectUri;

    @Override
    public Set<String> getResourceIds() {
        if (StringUtils.isEmpty(this.resourceIds)) {
            return new HashSet<>();
        } else {
            return StringUtils.commaDelimitedListToSet(this.resourceIds);
        }
    }

    @Override
    public boolean isSecretRequired() {
        return !StringUtils.isEmpty(this.clientSecret);
    }

    @Override
    public boolean isScoped() {
        return this.getScope().size() > 0;
    }

    @Override
    public Set<String> getScope() {
        return StringUtils.commaDelimitedListToSet(this.scope);
    }

    @Override
    public Set<String> getAuthorizedGrantTypes() {
        return StringUtils.commaDelimitedListToSet(this.authorizedGrantTypes);
    }

    @Override
    public Set<String> getRegisteredRedirectUri() {
        return StringUtils.commaDelimitedListToSet(this.registeredRedirectUri);
    }

    @Override
    public Collection<GrantedAuthority> getAuthorities() {
        Set<String> set = StringUtils.commaDelimitedListToSet(this.authorities);
        Set<GrantedAuthority> result = new HashSet<>();
        set.forEach(authority -> result.add((GrantedAuthority) () -> authority));
        return result;
    }

    @Override
    public boolean isAutoApprove(String scope) {
        return this.getAutoApproveScope().contains(scope);
    }

    @Override
    public Map<String, Object> getAdditionalInformation() {
        if (this.additionalInformation == null) {
            return new HashMap<>(0);
        }
        return JsonParserFactory.create().parseMap(this.additionalInformation);
    }
}
